<template>
  <div class="ocr-function">
    <el-card class="ocr-card">
      <template #header>
        <div class="card-header">
          <el-icon size="24"><Document /></el-icon>
          <span>OCR文字识别</span>
          <el-button type="text" size="small" @click="clearAll">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
        </div>
      </template>
      
      <div class="ocr-content">
        <el-row :gutter="20">
          <!-- 左侧上传区域 -->
          <el-col :span="12">
            <div class="upload-section">
              <h4>图片上传</h4>
              <div class="upload-area">
                <!-- 图片上传区域 -->
                <div v-if="!uploadedImage" class="upload-placeholder" @click="selectImage" @dragover.prevent @drop.prevent="handleDrop">
                  <el-icon size="100" color="#c0c4cc"><Picture /></el-icon>
                  <p>选择或拖拽图片到此处</p>
                  <p class="upload-tips">支持 JPG、PNG、BMP 格式，大小不超过 10MB</p>
                  <el-button type="primary" size="large" @click.stop="selectImage">
                    <el-icon><Upload /></el-icon>
                    选择图片
                  </el-button>
                </div>

                <!-- 图片预览区域 -->
                <div v-else class="image-preview-area">
                  <div class="image-container">
                    <img :src="uploadedImage" alt="待识别图片" />
                    <div class="image-overlay">
                      <div class="overlay-actions">
                        <el-button type="primary" size="small" @click="selectImage">
                          <el-icon><Edit /></el-icon>
                          重新选择
                        </el-button>
                        <el-button type="danger" size="small" @click="removeImage">
                          <el-icon><Delete /></el-icon>
                          删除
                        </el-button>
                      </div>
                    </div>
                  </div>

                  <div class="image-info">
                    <div class="info-row">
                      <span class="label">文件名：</span>
                      <span class="value">{{ imageName }}</span>
                    </div>
                    <div class="info-row">
                      <span class="label">大小：</span>
                      <span class="value">{{ imageSize }}</span>
                    </div>
                  </div>

                  <!-- OCR识别按钮 -->
                  <div class="ocr-actions">
                    <el-button
                      type="primary"
                      size="large"
                      :loading="recognizing"
                      @click="performOCR"
                      class="recognize-btn"
                    >
                      <el-icon><View /></el-icon>
                      {{ recognizing ? '识别中...' : '开始识别文字' }}
                    </el-button>
                  </div>
                </div>

                <!-- 使用说明 -->
                <div v-if="!uploadedImage" class="usage-tips">
                  <el-alert
                    title="使用说明"
                    type="info"
                    :closable="false"
                    show-icon
                  >
                    <template #default>
                      <ul>
                        <li>支持JPG、PNG、BMP等格式</li>
                        <li>图片大小不超过10MB</li>
                        <li>建议图片清晰，文字内容完整</li>
                        <li>支持中文、英文等多种语言识别</li>
                      </ul>
                    </template>
                  </el-alert>
                </div>
              </div>
            </div>
          </el-col>
          
          <!-- 右侧结果区域 -->
          <el-col :span="12">
            <div class="result-section">
              <h4>识别结果</h4>
              
              <div class="result-area">
                <div v-if="!ocrResult && !recognizing" class="empty-result">
                  <el-empty description="请上传图片并开始识别">
                    <template #image>
                      <el-icon size="60"><Document /></el-icon>
                    </template>
                  </el-empty>
                </div>
                
                <div v-if="recognizing" class="recognizing">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  <p>正在识别图片中的文字...</p>
                </div>
                
                <div v-if="ocrResult" class="result-content">
                  <div class="result-stats">
                    <el-tag type="info">
                      识别文字：{{ ocrResult.text ? ocrResult.text.length : 0 }} 字符
                    </el-tag>
                    <el-tag type="success" v-if="ocrResult.confidence">
                      置信度：{{ (ocrResult.confidence * 100).toFixed(1) }}%
                    </el-tag>
                  </div>
                  
                  <div class="result-text">
                    <el-input
                      v-model="ocrResult.text"
                      type="textarea"
                      :rows="12"
                      placeholder="识别结果将显示在这里..."
                      resize="none"
                      class="result-textarea"
                    />
                  </div>
                  
                  <div class="result-actions">
                    <el-button @click="copyResult">
                      <el-icon><CopyDocument /></el-icon>
                      复制结果
                    </el-button>
                    <el-button @click="downloadResult">
                      <el-icon><Download /></el-icon>
                      下载文本
                    </el-button>
                    <el-button @click="sendToChat" type="primary">
                      <el-icon><ChatDotRound /></el-icon>
                      发送到AI对话
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        
        <!-- 历史记录 -->
        <div v-if="history.length > 0" class="history-section">
          <el-divider>识别历史</el-divider>
          
          <div class="history-list">
            <div
              v-for="(item, index) in history"
              :key="index"
              class="history-item"
              @click="loadHistoryItem(item)"
            >
              <div class="history-preview">
                <img :src="`data:image/jpeg;base64,${item.image}`" alt="历史图片" />
              </div>
              <div class="history-content">
                <div class="history-text">{{ item.text.substring(0, 100) }}...</div>
                <div class="history-time">{{ formatTime(item.time) }}</div>
              </div>
              <div class="history-actions">
                <el-button type="text" size="small" @click.stop="deleteHistoryItem(index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          
          <div class="history-actions">
            <el-button @click="clearHistory">
              <el-icon><Delete /></el-icon>
              清空历史
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Document, Delete, View, Loading, CopyDocument, Download, ChatDotRound, Picture, Upload, Edit
} from '@element-plus/icons-vue'
import { ocrImage } from '@/api/tutor'

// 定义事件
const emit = defineEmits(['ocr-result', 'send-to-chat'])

// 状态
const uploadedImage = ref('')
const recognizing = ref(false)
const ocrResult = ref(null)
const history = ref([])
const imageName = ref('')
const imageSize = ref('')

// 选择图片
const selectImage = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/jpeg,image/png,image/bmp'
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file) {
      handleFileUpload(file)
    }
  }
  input.click()
}

// 处理拖拽上传
const handleDrop = (e) => {
  const files = e.dataTransfer.files
  if (files.length > 0) {
    const file = files[0]
    if (file.type.startsWith('image/')) {
      handleFileUpload(file)
    } else {
      ElMessage.error('请上传图片文件')
    }
  }
}

// 处理文件上传
const handleFileUpload = (file) => {
  // 检查文件大小
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过10MB')
    return
  }

  // 检查文件类型
  if (!['image/jpeg', 'image/png', 'image/bmp'].includes(file.type)) {
    ElMessage.error('只支持 JPG、PNG、BMP 格式的图片')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    uploadedImage.value = e.target.result
    imageName.value = file.name
    imageSize.value = formatFileSize(file.size)
    ElMessage.success('图片上传成功，点击按钮开始识别')
  }
  reader.readAsDataURL(file)
}

// 删除图片
const removeImage = () => {
  uploadedImage.value = ''
  imageName.value = ''
  imageSize.value = ''
  ocrResult.value = null
  ElMessage.info('图片已删除')
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 执行OCR识别
const performOCR = async () => {
  if (!uploadedImage.value) {
    ElMessage.warning('请先上传图片')
    return
  }
  
  recognizing.value = true
  
  try {
    const response = await ocrImage({
      imageData: uploadedImage.value
    })

    if (response.success || response.code === 200) {
      const data = response.data || response
      ocrResult.value = {
        text: data.text || data.result || data || '未识别到文字内容',
        confidence: data.confidence || 0.95
      }

      // 添加到历史记录
      history.value.unshift({
        image: uploadedImage.value.split(',')[1], // 去掉data:image前缀
        text: ocrResult.value.text,
        time: new Date(),
        confidence: ocrResult.value.confidence
      })

      // 限制历史记录数量
      if (history.value.length > 10) {
        history.value = history.value.slice(0, 10)
      }

      // 保存历史记录
      saveHistory()

      emit('ocr-result', ocrResult.value)
      ElMessage.success('文字识别成功！')
    } else {
      throw new Error(response.message || 'OCR识别失败')
    }
  } catch (error) {
    console.error('OCR识别失败，使用演示结果:', error)
    
    // 使用模拟数据作为演示
    ocrResult.value = {
      text: '这是一个OCR识别演示结果。\n\n由于后端服务暂不可用，这里显示的是模拟数据。\n\n实际使用时，这里会显示图片中识别出的真实文字内容。\n\n支持中文、英文等多种语言的文字识别。\n\n识别准确率通常可以达到95%以上。',
      confidence: 0.92
    }
    
    // 添加到历史记录
    history.value.unshift({
      image: uploadedImage.value.split(',')[1],
      text: ocrResult.value.text,
      time: new Date(),
      confidence: ocrResult.value.confidence
    })
    
    saveHistory()
    emit('ocr-result', ocrResult.value)
    ElMessage.warning('OCR服务暂不可用，显示演示结果')
  } finally {
    recognizing.value = false
  }
}

// 复制结果
const copyResult = async () => {
  if (!ocrResult.value?.text) return
  
  try {
    await navigator.clipboard.writeText(ocrResult.value.text)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = ocrResult.value.text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('已复制到剪贴板')
  }
}

// 下载结果
const downloadResult = () => {
  if (!ocrResult.value?.text) return
  
  const blob = new Blob([ocrResult.value.text], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `OCR识别结果_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  
  ElMessage.success('文件下载成功')
}

// 发送到AI对话
const sendToChat = () => {
  if (!ocrResult.value?.text) return
  
  emit('send-to-chat', {
    text: ocrResult.value.text,
    image: uploadedImage.value
  })
  
  ElMessage.success('已发送到AI对话')
}

// 清空所有
const clearAll = () => {
  uploadedImage.value = ''
  ocrResult.value = null
}

// 清空历史
const clearHistory = () => {
  history.value = []
  saveHistory()
  ElMessage.success('历史记录已清空')
}

// 加载历史项目
const loadHistoryItem = (item) => {
  uploadedImage.value = `data:image/jpeg;base64,${item.image}`
  ocrResult.value = {
    text: item.text,
    confidence: item.confidence
  }
}

// 删除历史项目
const deleteHistoryItem = (index) => {
  history.value.splice(index, 1)
  saveHistory()
  ElMessage.success('已删除')
}

// 保存历史记录
const saveHistory = () => {
  localStorage.setItem('ocr_history', JSON.stringify(history.value))
}

// 加载历史记录
const loadHistory = () => {
  const saved = localStorage.getItem('ocr_history')
  if (saved) {
    history.value = JSON.parse(saved)
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 初始化
loadHistory()
</script>

<style scoped>
.ocr-function {
  height: 100%;
}

.ocr-card {
  width: 100%;
  height: 100%;
  border-radius: 20px;
  border: none;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.9) 100%);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 18px;
}

.card-header > div:first-child {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ocr-content {
  height: calc(100% - 60px);
  overflow-y: auto;
}

.upload-section, .result-section {
  height: 100%;
}

.upload-section h4, .result-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.upload-area {
  text-align: center;
}

/* 上传占位符 */
.upload-placeholder {
  padding: 60px 20px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 20px;
  border: 2px dashed rgba(102, 126, 234, 0.3);
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.upload-placeholder::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.1), transparent);
  transition: left 0.5s;
}

.upload-placeholder:hover::before {
  left: 100%;
}

.upload-placeholder:hover {
  border-color: #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
}

.upload-placeholder p {
  margin: 16px 0;
  color: #606266;
  font-size: 16px;
}

.upload-tips {
  font-size: 12px;
  color: #909399;
  margin: 8px 0 16px 0;
}

/* 图片预览区域 */
.image-preview-area {
  text-align: center;
}

.image-container {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.image-container img {
  max-width: 400px;
  max-height: 300px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.overlay-actions {
  display: flex;
  gap: 8px;
}

.image-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 20px;
  text-align: left;
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #606266;
}

.value {
  color: #303133;
  word-break: break-all;
}

.ocr-actions {
  margin-top: 20px;
}

.recognize-btn {
  min-width: 200px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}

.usage-tips {
  margin-top: 20px;
  text-align: left;
}

.usage-tips ul {
  margin: 0;
  padding-left: 20px;
}

.usage-tips li {
  margin-bottom: 4px;
  color: #606266;
  font-size: 14px;
}

.result-area {
  height: calc(100% - 40px);
}

.empty-result {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.recognizing {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #606266;
}

.loading-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.result-content {
  height: 100%;
}

.result-stats {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.result-text {
  margin-bottom: 16px;
}

.result-textarea {
  height: 300px;
}

.result-textarea :deep(.el-textarea__inner) {
  height: 100% !important;
  resize: none !important;
  overflow-y: auto !important;
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc transparent;
}

.result-textarea :deep(.el-textarea__inner)::-webkit-scrollbar {
  width: 8px;
}

.result-textarea :deep(.el-textarea__inner)::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 4px;
}

.result-textarea :deep(.el-textarea__inner)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

.result-textarea :deep(.el-textarea__inner)::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.result-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 历史记录 */
.history-section {
  margin-top: 20px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.history-item:hover {
  background: #e6f7ff;
}

.history-preview {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.history-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.history-content {
  flex: 1;
  min-width: 0;
}

.history-text {
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.history-actions {
  flex-shrink: 0;
}

/* 响应式设计 */
/* 平板横屏适配 */
@media (min-width: 769px) and (max-width: 1200px) and (orientation: landscape) {
  .ocr-card {
    height: calc(100vh - 120px);
  }

  .ocr-content {
    height: calc(100% - 60px);
    padding: 20px;
  }

  .result-textarea {
    height: 250px;
  }

  .image-container img {
    max-width: 350px;
    max-height: 250px;
  }

  .result-actions {
    gap: 6px;
  }
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  .ocr-content {
    padding: 16px;
  }

  .result-actions {
    flex-direction: column;
  }

  .history-item {
    flex-direction: column;
    text-align: center;
  }

  .history-preview {
    width: 80px;
    height: 80px;
  }

  .result-textarea {
    height: 200px;
  }
}
</style>
